<template>
  <div class="wrapper">
    <section class="data-operates data-operates-top">
      <p>Manually Confirm Selected Items:</p>
      <Button size="large" shape="circle" type="primary" @click="exportSelectedItemsFunc" class="btn">Export Selected Items</Button>
      <Button size="large" shape="circle" type="primary"  @click="importItemsModal = true" class="btn">Import Confirmation</Button>
    </section>

    <section class="data-operates data-operates-batch-update clearfix">
      <div class="cnt-left">
        <div class="batch-update-status">
          <p>Batch Update Selected Items:</p>
          <RadioGroup v-model="batchUpdateStatus" @on-change="batchUpdate">
            <Radio label="stock confirmed">Stock Confirmed</Radio>
            <Radio label="back ordered">Back Ordered</Radio>
            <Radio label="size discontinued">Size Discontinued</Radio>
            <Radio label="model discontinued">Model Discontinued</Radio>
            <Radio label="color discontinued">Color Discontinued</Radio>
          </RadioGroup>
        </div>
      </div>
      <div class="cnt-right">
        <Button type="primary" size="large" long :disabled="confirmBtnDisable" @click="submitConfirmedData">Update Confirm</Button>
      </div>
      <Modal
        v-model="batchUpdateModal"
        title="Warning"
        @on-ok="batchUpdateModalClose"
        @on-cancel="batchUpdateModalClose">
        <p>Please select item !</p>
      </Modal>
    </section>

    <section class="table-size">
      <div class="table-size-cnt">
        Table size
        <Radio-group v-model="tableSize" type="button">
          <Radio label="large">large</Radio>
          <Radio label="default">medium(default)</Radio>
          <Radio label="small">small</Radio>
        </Radio-group>
      </div>
      <p class="items-remain" v-show="waitToConfirmDada"><span class="item-num">{{ waitToConfirmDada.length }}</span> Items Remain</p>
    </section>
    <section class="data-list">
      <Table border no-data-text :size="tableSize" :loading="tableDataloading" ref="waitToConfirm" :columns="tableColumns" :data="waitToConfirmDada" @on-select="addSelectedItem"  @on-select-cancel="removeSelectedItem" @on-selection-change="allSelectedOperate" v-if="waitToConfirmDada.length"></Table>
      <div v-show="notableDataTip">
        <Alert type="warning" class="no-data-alter">
          A warning prompt
          <template slot="desc">
            No data for wait to confirm!!
          </template>
        </Alert>
      </div>
    </section>

    <Modal v-model="importItemsModal" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>Import Item Confirmation Excel File</span>
      </p>
      <div style="text-align:center">
        <Upload
          ref="excelFileUploadForm"
          type="drag"
          :format="['xlsx']"
          :on-format-error="handleFormatError"
          action="http://mock-data-data-api/api/supplier-PO/wait-to-confirm/excel-import" :before-upload="fileBeforeUpload"  :on-success="fileUploadSuccess" :on-error ="fileUploadError" :on-progress="fileUploadProgress">
          <div style="padding: 20px 0">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>Click or drag files here to upload</p>
          </div>
        </Upload>
      </div>
      <div slot="footer"></div>
    </Modal>

    <Modal v-model="dataPreviewModal" width="80%" class="data-preview-modal">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>Items Cofirmation Preview</span>
      </p>
      <div style="text-align:center">
        <section v-if="preApprovedWaitConfirmData.length">
          <h3 class="title successful">Approved</h3>
          <Table border no-data-text :size="tableSize" :loading="tableDataloading" :columns="preCheckTableColumns" :data="preApprovedWaitConfirmData"></Table>
        </section>
        <section class="warning-items" v-if="preNotApprovedWaitConfirmData.length">
          <h3 class="title error">Not Approved, please update the status.</h3>
          <Table border no-data-text :size="tableSize" :loading="tableDataloading" :columns="preCheckTableColumns" :data="preNotApprovedWaitConfirmData"></Table>
        </section>
      </div>
      <div slot="footer" class="data-preview-btn-group">
        <Button type="default" size="large"  @click="cancelPreCheckWaitConfirmData">Cancel</Button>
        <Button type="primary" size="large"  @click="" v-show="preApprovedWaitConfirmData.length > 0 && preNotApprovedWaitConfirmData.length == 0">Confirm</Button>
      </div>
    </Modal>

    <transition name="router-slid" mode="out-in">
      <div>
        <keep-alive>
          <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
      </div>
    </transition>
  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex';
  import { modalInstance } from '@/components/mixin';
  import { getSupplierPO, submitWaitToConfirm, waitToConfirmExcelExport } from '@/api/index';
  export default {
  	name: 'WaitToConfirm',
    mixins: [ modalInstance ],
    data () {
  		return {
        tableDataloading: true,
        notableDataTip: false,
        tableSize: 'default',
        submitTipMsg: [],
        submitTipMsgShow: false,
        waitToConfirmDada: [],
        exportSelectedItems: [],
        importItemsModal: false,
        loadingStatus: false,
        uploadExcelResponseData: [],
        confirmBtnDisable: true,
        batchUpdateStatus: 'wait to update',
        batchUpdateModal: false,
        dataPreviewModal: false,
        tableColumns: [
          {
            type: 'selection',
            width: 60,
            align: 'center',
            fixed: 'left'
          },
          {
            title: 'Tag',
            align: 'center',
            width: 90,
            fixed: 'left',
            key: 'tag'
          },
          {
            title: 'UPC',
            align: 'center',
            minWidth: 125,
            fixed: 'left',
            key: 'UPC'
          },
          {
            title: 'From PO',
            align: 'center',
            minWidth: 150,
            key: 'from_PO'
          },
          {
            title: 'Create Date',
            align: 'center',
            minWidth: 150,
            key: 'create_date'
          },
          {
            title: 'Category',
            align: 'center',
            width: 160,
            key: 'category'
          },
          {
            title: 'Brand',
            align: 'center',
            minWidth: 130,
            key: 'brand'
          },
          {
            title: 'Product Code',
            width: 85,
            align: 'center',
            key: 'product_code'
          },
          {
            title: 'Product Name',
            minWidth: 185,
            key: 'product_name'
          },
          {
            title: 'Colour Code',
            width: 80,
            align: 'center',
            key: 'colour_code'
          },
          {
            title: 'Size',
            width: 65,
            align: 'center',
            key: 'size'
          },
          {
            title: 'Order QTY',
            width: 70,
            align: 'center',
            key: 'order_QTY'
          },
          {
            title: 'Exp. QTY',
            width: 70,
            align: 'center',
            key: 'Exp_QTY'
          },
          {
            title: 'Status',
            align: 'center',
            width:170,
            render: (h, params) => {
              let optionArr = [{text: 'wait to update', value: ''}, {text: 'stock confirmed', value: 1}, {text: 'back ordered', value: 0}, {text: 'size discontinued', value: 0}, {text: 'model discontinued', value: 0}, {text: 'color discontinued', value: 0}];
                return h('select', {
                  on:{
                    change: (e) => {
                    	let inputValue = e.target.value;
                      this.batchUpdateStatus = 'wait to update';
                      this.confirmBtnDisable = (e.target.value != 'wait to update') ? false : true;
                      if ( inputValue == 'wait to update'){
                        delete params.row._checked;
                        delete params.row.Exp_QTY;
                      } else if (inputValue == 'stock confirmed') {
                        params.row.Exp_QTY = '1';
                        params.row._checked = true;
                      } else if (inputValue == 'back ordered' || 'size discontinued' || 'model discontinued' || 'color discontinued') {
                        params.row.Exp_QTY = '0';
                        params.row._checked = true;
                      }
                      params.row.status_text = inputValue;
                      this.waitToConfirmDada.splice(params.index, 1, params.row);
                    }
                  }
                }, optionArr.map(item => {
                  if (params.row.status_text == item.text) {
                    item.selected = 'selected';
                  } else {
                    item.selected = '';
                  }
                  return h('option', {
                    domProps: {
                      value: item.text,
                      selected: item.selected
                    },
                  }, item.text);
                }));
            }
          }
        ],
        preCheckTableColumns: [
          {
            title: 'Tag',
            align: 'center',
            width: 90,
            fixed: 'left',
            key: 'tag'
          },
          {
            title: 'UPC',
            align: 'center',
            minWidth: 125,
            fixed: 'left',
            key: 'UPC'
          },
          {
            title: 'From PO',
            align: 'center',
            minWidth: 150,
            key: 'from_PO'
          },
          {
            title: 'Create Date',
            align: 'center',
            minWidth: 150,
            key: 'create_date'
          },
          {
            title: 'Category',
            align: 'center',
            width: 160,
            key: 'category'
          },
          {
            title: 'Brand',
            align: 'center',
            minWidth: 130,
            key: 'brand'
          },
          {
            title: 'Product Code',
            width: 85,
            align: 'center',
            key: 'product_code'
          },
          {
            title: 'Product Name',
            minWidth: 185,
            key: 'product_name'
          },
          {
            title: 'Colour Code',
            width: 80,
            align: 'center',
            key: 'colour_code'
          },
          {
            title: 'Size',
            width: 65,
            align: 'center',
            key: 'size'
          },
          {
            title: 'Order QTY',
            width: 70,
            align: 'center',
            key: 'order_QTY'
          },
          {
            title: 'Exp. QTY',
            width: 70,
            align: 'center',
            key: 'Exp_QTY'
          },
          {
            title: 'Status',
            align: 'center',
            width: 170,
            key: 'status_text'
          }
        ],
        preApprovedWaitConfirmData: [
          {
            'tag': '3987805',
            'UPC': '6646896755314',
            'from_PO': 'Marco_20180611_2',
            'category': 'Designer Glasses',
            'brand': 'Tom Ford',
            'product_code': '267485',
            'product_name': 'Tom Ford FT5352',
            'colour_code': '52',
            'size': '54',
            'order_QTY': 1,
            'Exp_QTY': 0,
            "status_text": 'Size Discontinued'
          },
          {
            'tag': '3987804',
            'UPC': '7507790772695',
            'from_PO': 'Marco_20180611_2',
            'category': 'Designer Glasses',
            'brand': 'Calvin Klein',
            'product_code': '272798',
            'product_name': 'Calvin Klein CK7973',
            'colour_code': '306',
            'size': '51',
            'order_QTY': 1,
            'Exp_QTY': 1,
            "status_text": 'Stock confirmed'
          },
          {
            'tag': '3987803',
            'UPC': '7507790772696',
            'from_PO': 'Marco_20180611_2',
            'category': 'Designer Glasses',
            'brand': 'Balenciaga',
            'product_code': '291278',
            'product_name': 'Balenciaga BA5043',
            'colour_code': '1',
            'size': '52',
            'order_QTY': 1,
            'Exp_QTY': 0,
            "status_text": 'Color Discontinued'
          }
        ],
        preNotApprovedWaitConfirmData: [
          {
            'tag': '3987806',
            'UPC': '750779077269666',
            'from_PO': 'Marco_20180611_2',
            'category': 'Designer Glasses',
            'brand': 'Balenciaga',
            'product_code': '291278',
            'product_name': 'Balenciaga BA5043',
            'colour_code': '1',
            'size': '52',
            'order_QTY': 1,
            'Exp_QTY': '',
            "status_text": ''
          }
        ],
      }
    },
    computed:{
      ...mapState([ 'curWaitToConfirmData'])
    },
    created () {
      getSupplierPO('wait-to-confirm').then(res => {
        this.$Loading.start();
        let resObj = res.data;
        if (!!resObj) {
          this.$Loading.finish();
          this.tableDataloading = false;
          this.waitToConfirmDada =  resObj.data;
        } else {
          this.$Loading.error();
          this.notableDataTip = true;
        }
      });

    },
    methods: {
      ...mapMutations([ 'RECORD_WAITTOCONFIRM']),
      exportSelectedItemsFunc () {
      	this.exportSelectedItems = [];
        this.waitToConfirmDada.forEach(data => {
          if (data._checked) {
            this.exportSelectedItems.push(data);
          }
        });
        if (this.exportSelectedItems.length == 0) {
          this.modalInstance('warning', 'warning', 'Please select item !');
        	return;
        }
        this.exportSelectedItems.forEach(item => {
        	item.alter_options = '';
        });
        waitToConfirmExcelExport(this.exportSelectedItems).then(res => {
          this.$Loading.start();
        	let resData = res.data;
        	if (resData.status_code == 1) {
            this.$Loading.finish();
            this.$Message.success('Export excel success!');
            this.modalInstance('success', 'Success', 'Export file success!');
          } else {
            this.$Loading.error();
            this.$Message.error('Export excel fail!');
          }
        });
      },
      batchUpdate() {
        let alreadyCheckedItem = this.waitToConfirmDada.some(function (item) {
          return item._checked;
        });
        if (!alreadyCheckedItem) {
          this.batchUpdateModal = true;
          return;
        }
      	let statusCode;
      	switch (this.batchUpdateStatus) {
          case 'stock confirmed':
            statusCode = 1;
            break;
          case 'back ordered':
            statusCode = 0;
            break;
          case 'size discontinued':
            statusCode = 0;
            break;
          case 'model discontinued':
            statusCode = 0;
            break;
          case 'color discontinued':
            statusCode = 0;
            break;
          default:
            statusCode = '';
            break;
        }
        this.waitToConfirmDada.forEach((item, index) => {
          if(item._checked) {
            let obj = item;
            obj.Exp_QTY = statusCode;
            obj.status_text = this.batchUpdateStatus;
            this.waitToConfirmDada.splice(index, 1, obj);
          }
        });
      },
      batchUpdateModalClose() {
        this.batchUpdateModal = false;
        this.batchUpdateStatus = 'wait to update';
      },
      addSelectedItem(selection, row){
        selection.forEach((selectionItem) => {
          this.waitToConfirmDada.forEach(data => {
            if (selectionItem.tag == data.tag) {
            	data._checked = true;
            }
          })
        });
      },
      removeSelectedItem(selection, row) {
          this.waitToConfirmDada.forEach((data, index) => {
            if (row.tag == data.tag) {
              delete data._checked;
              delete data.Exp_QTY;
              data.status_text = 'wait to update';
            }
          })
      },
      allSelectedOperate (selection) {
        this.batchUpdateStatus = 'wait to update';
        let newWaitToConfirmDada;
      	if (selection.length == 0) {
          this.confirmBtnDisable = true;
          newWaitToConfirmDada = [];
          this.waitToConfirmDada.forEach((data, index) => {
            delete data._checked;
            delete data.Exp_QTY;
            data.status_text = 'wait to update';
            newWaitToConfirmDada.push(data);
          });
          return false;
        } else if (selection.length == this.waitToConfirmDada.length) {
          this.confirmBtnDisable = false;
          newWaitToConfirmDada = []
          this.waitToConfirmDada.forEach(data => {
            data._checked = true;
            newWaitToConfirmDada.push(data);
          })
          return false;
        } else {
          this.confirmBtnDisable = false;
      		return false;
        }
        this.waitToConfirmDada = newWaitToConfirmDada;
      },
      submitConfirmedData() {
      	let dataArray = [];
      	let willSubmitDataArrray = [];
        this.submitTipMsg = [];
      	this.waitToConfirmDada.forEach((item, index) => {
          if ((!item.status_text && item._checked) || (item.status_text == 'wait to update' && item._checked)) {
            dataArray.push(item);
          	this.submitTipMsg.push(item);
          } else if (item.status_text && item.status_text != 'wait to update' && item._checked) {
            willSubmitDataArrray.push(item);
          } else if (!item.Exp_QTY) {
            dataArray.push(item);
          }
        });
        if (this.submitTipMsg.length > 0) {
          let submitModalTipHTML = '<p>Please check the list of Status</p>';
          this.submitTipMsg.forEach(item => {
            submitModalTipHTML += '<p>UPC: ' + item.UPC +'<p>'
          });
          this.modalInstance('error', 'error', submitModalTipHTML);
          this.$Message.error('Submit fail!');
          return;
        }
        this.waitToConfirmDada = dataArray;
        this.RECORD_WAITTOCONFIRM(this.waitToConfirmDada);
        if (willSubmitDataArrray.length > 0) {
          submitWaitToConfirm(willSubmitDataArrray).then(res => {
            this.$Loading.start();
            let resData = res.data;
            if(resData.status_code == 1) {
              this.$Message.success('Submit success!');
              this.$Loading.finish();
              this.confirmBtnDisable = true;
//              this.$router.push('/supplier-PO/confirmed');
            } else {
              this.$Message.error('Submit fail!');
              this.$Loading.error();
            }
          })
        } else {
          this.modalInstance('error', 'error', 'Please select item');
          this.$Message.error('Submit fail!');
          this.$Loading.error();
        }
      },
      cancelPreCheckWaitConfirmData () {
      	this.dataPreviewModal = false;
      },
      fileBeforeUpload (file) {
        this.$refs.excelFileUploadForm.clearFiles();
      },
      fileUploadProgress (event, file, fileList) {
        console.log('fileUploadProgress',event)
        console.log('fileUploadProgress',file)
        console.log('fileUploadProgress',fileList)
      },
      fileUploadSuccess (response, file) {
        this.dataPreviewModal = true;
      	console.log('upload file', file)
      	this.uploadExcelResponseData = response.data;
      	this.importItemsModal = false;
        this.$Message.success('File Upload Success');
        this.uploadExcelResponseData.forEach(resData => {
          this.waitToConfirmDada.forEach((item, index) => {
          	if (resData.tag == item.tag) {
          		item._checked = true;
              item.Exp_QTY = resData.Exp_QTY;
              item.status_text = resData.status_text;
              this.waitToConfirmDada.splice(index, 1, item)
            }
          })
        });
      },
      fileUploadError(error, file, fileList) {
        this.modalInstance('warning', 'warning', error);
      },
      handleFormatError (file) {
        this.modalInstance('error', 'The file format is incorrect', 'File format of ' + file.name + ' is incorrect, please select xlsx.');
      }
    },
    watch: {
      waitToConfirmDada: function (val) {
        let alreadyCheckedItem = val.some(function (item) {
          return item._checked;
        });
        if (alreadyCheckedItem) {
          this.confirmBtnDisable = false;
        } else {
          this.confirmBtnDisable = true;
        }
      	if (val.length == 0) {
          this.notableDataTip = true;
          this.confirmBtnDisable = true;
          this.$router.push('/supplier-PO/confirmed');
        }
        this.RECORD_WAITTOCONFIRM(val);
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../../assets/sass/mixin';
  .data-operates-top {
    @include fj(flex-start);
    p, .btn {
      margin-right: 10px;
    }
  }
  .data-operates-batch-update {
    padding-bottom: 10px;
  }
  .batch-update-status {
    @include fj(flex-start);
  }
  .data-preview-modal {
    .title {
      padding-bottom: 5px;
      text-align: left;
    }
    .warning-items {
      margin-top: 20px;
    }
    .successful {
      color: #19be6b;
    }
    .error {
      color: #cc0000;
    }
  }
  .data-preview-btn-group {
    text-align: center;
  }
</style>
